﻿using AutoMapper;
using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using System.Collections.Generic;
using System.Security;

namespace R.FarmSmartSleep.RBAC.API.Apliction.Command
{
    public class EmployeeRouterHandler:IRequestHandler<EmployeeRouterCommon,Result>
    {
        private readonly IBaseRepository<EmployeeRole> employeeRolesRep;
        private readonly IBaseRepository<Employee> employeeRep;
        private readonly IMapper mapper;

        public EmployeeRouterHandler(IBaseRepository<EmployeeRole> employeeRolesRep ,IBaseRepository<Employee> employeeRep, IMapper mapper)
        {
            this.employeeRolesRep= employeeRolesRep;
            this.employeeRep = employeeRep;
            this.mapper = mapper;
        }

        public  async Task<Result> Handle(EmployeeRouterCommon request, CancellationToken cancellationToken)
        {

            var Result = new Result() { Code = (int)CodeEnum.add };
            try
            {
                Employee employee = mapper.Map<Employee>(request);
                employee.CreateTime = DateTime.Now;
                var list = await employeeRep.AddAsync(employee);
                if (list>0)
                {
                    Result.Code = (int)CodeEnum.success;
                    Result.Messege = "添加成功";
                    /// 修改权限
                    foreach (var item in request.RolesIds)
                    {
                        // 修改权限
                        await employeeRolesRep.AddAsync(new EmployeeRole
                        {
                            EmployeeId = employee.EmployeeId,
                            RolesId = item
                        });
                    }
                }
            }
            catch (Exception)
            {
                Result.Messege = "添加失败";
                throw;
            }

            return Result;

        }
    }
}
